package com.raycloud.java.dada.util;

import com.alibaba.fastjson.JSON;
import com.sun.tools.internal.xjc.reader.xmlschema.bindinfo.BIConversion;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.io.IOException;
import java.util.Map;

/**
 * Created by:  intelliJ IDEA
 *
 * @Author albert
 * @Description: 请求执行类
 * @Date:2017/6/9 下午5:18
 * @package:com.test.java.dada.util
 * @Modified By:
 */
public class HttpRequestUtil {
    private static   Logger Logger = LoggerFactory.getLogger(HttpRequestUtil.class);

    private final static String CONTENT_TYPE_TEXT_JSON = "text/json";


    /**
     * 使用httpClient请求接口
     * @param url
     * @param param
     * @return
     * @throws IOException
     */
    public  String methodPost(String url, Map<String, Object> param) throws  IOException {
        CloseableHttpClient client = HttpClients.createDefault();
        //设置超时时间 setConnectTimeout：设置连接超时时间，单位毫秒
        //setConnectionRequestTimeout：设置从connect Manager获取Connection 超时时间，
        // 单位毫秒。这个属性是新加的属性，因为目前版本是可以共享连接池的
        //setSocketTimeout：请求获取数据的超时时间，单位毫秒。 如果访问一个接口，多少时间内无法返回数据，就直接放弃此次调用。
//        RequestConfig requestConfig = RequestConfig.custom()
//                .setConnectTimeout(5000).setConnectionRequestTimeout(3000)
//                .setSocketTimeout(5000).build();
        HttpPost httpPost = new HttpPost(url);
//        httpPost.setConfig(requestConfig);

        httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
        String parameter = JSON.toJSONString(param);
        StringEntity se = new StringEntity(parameter, ContentType.APPLICATION_JSON);
        se.setContentType(CONTENT_TYPE_TEXT_JSON);
        httpPost.setEntity(se);
        CloseableHttpResponse response = client.execute(httpPost);
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity, "UTF-8");
        httpPost.releaseConnection();
        Logger.info("达达请求返回{}",result);
        return result;
    }


}